package com.twinkle.xiaohashu.kv.biz.service.impl;

import com.twinkle.framework.common.exception.BusinessException;
import com.twinkle.framework.common.response.Response;
import com.twinkle.xiaohashu.kv.biz.model.entity.NoteContent;
import com.twinkle.xiaohashu.kv.biz.model.repository.NoteContentRepository;
import com.twinkle.xiaohashu.kv.biz.service.NoteContentService;
import com.twinkle.xiaohashu.kv.dto.req.DeleteNoteContentReqDTO;
import com.twinkle.xiaohashu.kv.enums.ResponseCodeEnum;
import com.twinkle.xiaohashu.kv.dto.req.AddNoteContentReqDTO;
import com.twinkle.xiaohashu.kv.dto.req.FindNoteContentReqDTO;
import com.twinkle.xiaohashu.kv.dto.resp.FindNoteContentRspDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;

@Service
@Slf4j
public class NoteContentServiceImpl implements NoteContentService {
    @Resource
    private NoteContentRepository noteContentRepository;

    @Override
    public Response<?> addNoteContent(AddNoteContentReqDTO addNoteContentReqDTO) {
        String uuid = addNoteContentReqDTO.getUuid();
        String content = addNoteContentReqDTO.getContent();

        NoteContent noteContent = NoteContent.builder()
                .id(UUID.fromString(uuid))
                .content(content).build();
        noteContentRepository.save(noteContent);
        return Response.success();
    }

    @Override
    public Response<FindNoteContentRspDTO> findNoteContent(FindNoteContentReqDTO findNoteContentReqDTO) {
        String noteId = findNoteContentReqDTO.getUuid();
        Optional<NoteContent> optional = noteContentRepository.findById(UUID.fromString(noteId));
        if (!optional.isPresent()) {
            throw new BusinessException(ResponseCodeEnum.NOTE_CONTENT_NOT_FOUND);
        }
        NoteContent noteContent = optional.get();
        FindNoteContentRspDTO findNoteContentRspDTO = FindNoteContentRspDTO.builder()
                .uuid(noteContent.getId())
                .content(noteContent.getContent())
                .build();
        return Response.success(findNoteContentRspDTO);
    }

    @Override
    public Response<?> deleteNoteContent(DeleteNoteContentReqDTO deleteNoteContentReqDTO) {
        String noteId = deleteNoteContentReqDTO.getUuid();
        Optional<NoteContent> optional = noteContentRepository.findById(UUID.fromString(noteId));
        if (!optional.isPresent()) {
            throw new BusinessException(ResponseCodeEnum.NOTE_CONTENT_NOT_FOUND);
        }
        noteContentRepository.deleteById(UUID.fromString(noteId));
        return  Response.success();
    }
}
